/// 启动屏幕
/// 应用启动时展示的首屏
library;
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:chat_project/providers/auth_provider.dart';
import 'package:chat_project/config/theme_config.dart';
import 'package:chat_project/config/api_config.dart';
import 'package:flutter/foundation.dart' show kIsWeb;

class SplashScreen extends StatefulWidget {
  const SplashScreen({super.key});

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  bool _isLoading = false;
  bool _showServerConfig = false;
  bool _hasNavigated = false;
  final TextEditingController _serverIpController = TextEditingController();
  final TextEditingController _serverPortController = TextEditingController();
  
  @override
  void initState() {
    super.initState();
    
    // 初始化服务器配置控制器
    _serverIpController.text = ApiConfig.hostUrl.split(':')[0];
    _serverPortController.text = ApiConfig.hostUrl.split(':')[1];
    
    // 检查认证状态并导航
    _checkAuthState();
  }
  
  @override
  void dispose() {
    _serverIpController.dispose();
    _serverPortController.dispose();
    super.dispose();
  }
  
  // 检查认证状态
  Future<void> _checkAuthState() async {
    if (!mounted || _hasNavigated) return;
    
    setState(() => _isLoading = true);
    
    try {
      final authProvider = Provider.of<AuthProvider>(context, listen: false);
      print('开始检查认证状态...');
      
      // 使用真实API数据
      await authProvider.checkAuth(forceMockData: false);
      
      print('认证状态检查完成: ${authProvider.status}, 已认证=${authProvider.isAuthenticated}');
      
      // 使用单一计时器避免多次导航
      Future.delayed(const Duration(seconds: 1), () {
        if (!mounted || _hasNavigated) return;
        
        setState(() {
          _isLoading = false;
          _hasNavigated = true; // 标记已导航，防止重复
        });
        
        if (authProvider.isAuthenticated) {
          print('用户已登录，正在跳转到首页...');
          context.go('/home');
        } else {
          print('用户未登录，正在跳转到登录页...');
          context.go('/login');
        }
      });
    } catch (e) {
      print('初始化失败: $e');
      
      if (!mounted || _hasNavigated) return;
      
      setState(() {
        _isLoading = false;
        _hasNavigated = true;
      });
      
      // 显示错误消息
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('初始化失败: $e')),
        );
      }
      
      // 导航到登录页
      Future.delayed(const Duration(milliseconds: 500), () {
        if (mounted) {
          print('初始化失败后导航到登录页...');
          context.go('/login');
        }
      });
    }
  }
  
  // 更新服务器配置
  void _updateServerConfig() {
    final ip = _serverIpController.text.trim();
    final port = _serverPortController.text.trim();
    
    if (ip.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('服务器IP不能为空')),
      );
      return;
    }
    
    if (port.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('服务器端口不能为空')),
      );
      return;
    }
    
    try {
      // 更新API配置
      ApiConfig.configureForLAN(ip, port);
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('服务器配置已更新: ${ApiConfig.hostUrl}')),
      );
      
      setState(() {
        _showServerConfig = false;
        _hasNavigated = false; // 重置导航标志，允许重新检查认证状态
      });
      
      // 重新检查认证状态
      _checkAuthState();
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('更新服务器配置失败: $e')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeConfig.primaryColor,
      body: SafeArea(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Spacer(),
              
              // 应用Logo
              Container(
                width: 120,
                height: 120,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(24),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 20,
                      offset: const Offset(0, 10),
                    ),
                  ],
                ),
                child: const Icon(
                  Icons.chat_bubble_rounded,
                  size: 60,
                  color: ThemeConfig.primaryColor,
                ),
              ),
              
              const SizedBox(height: 24),
              
              // 应用名称
              const Text(
                '聊天应用',
                style: TextStyle(
                  fontSize: 28,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              
              const SizedBox(height: 8),
              
              // 应用标语
              Text(
                '随时随地保持联系',
                style: TextStyle(
                  fontSize: 16,
                  color: Colors.white.withOpacity(0.7),
                ),
              ),
              
              const Spacer(),
              
              // 加载指示器或服务器配置
              if (_isLoading)
                const CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                )
              else if (_showServerConfig)
                _buildServerConfigForm()
              else
                Column(
                  children: [
                    // 显示当前服务器配置
                    Text(
                      '当前服务器: ${ApiConfig.hostUrl}',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.white.withOpacity(0.7),
                      ),
                    ),
                    
                    const SizedBox(height: 16),
                    
                    // 显示操作按钮
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        ElevatedButton(
                          onPressed: _checkAuthState,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.white,
                            foregroundColor: ThemeConfig.primaryColor,
                            padding: const EdgeInsets.symmetric(
                              horizontal: 24,
                              vertical: 12,
                            ),
                          ),
                          child: const Text('继续'),
                        ),
                        
                        const SizedBox(width: 16),
                        
                        OutlinedButton(
                          onPressed: () {
                            setState(() => _showServerConfig = true);
                          },
                          style: OutlinedButton.styleFrom(
                            foregroundColor: Colors.white,
                            side: const BorderSide(color: Colors.white),
                            padding: const EdgeInsets.symmetric(
                              horizontal: 24,
                              vertical: 12,
                            ),
                          ),
                          child: const Text('设置服务器'),
                        ),
                      ],
                    ),
                  ],
                ),
              
              const SizedBox(height: 40),
              
              // 版本信息
              Text(
                'Version 1.0.0',
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.white.withOpacity(0.5),
                ),
              ),
              
              const SizedBox(height: 16),
            ],
          ),
        ),
      ),
    );
  }
  
  // 服务器配置表单
  Widget _buildServerConfigForm() {
    return Container(
      width: 280,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Text(
            '服务器配置',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: ThemeConfig.primaryColor,
            ),
          ),
          
          const SizedBox(height: 16),
          
          TextField(
            controller: _serverIpController,
            decoration: const InputDecoration(
              labelText: '服务器IP',
              hintText: '例如: 192.168.1.100',
              prefixIcon: Icon(Icons.computer),
              border: OutlineInputBorder(),
            ),
          ),
          
          const SizedBox(height: 16),
          
          TextField(
            controller: _serverPortController,
            decoration: const InputDecoration(
              labelText: '端口',
              hintText: '例如: 3000',
              prefixIcon: Icon(Icons.assignment_turned_in),
              border: OutlineInputBorder(),
            ),
            keyboardType: TextInputType.number,
          ),
          
          const SizedBox(height: 24),
          
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              TextButton(
                onPressed: () {
                  setState(() => _showServerConfig = false);
                },
                child: const Text('取消'),
              ),
              
              ElevatedButton(
                onPressed: _updateServerConfig,
                style: ElevatedButton.styleFrom(
                  backgroundColor: ThemeConfig.primaryColor,
                  foregroundColor: Colors.white,
                ),
                child: const Text('保存'),
              ),
            ],
          ),
        ],
      ),
    );
  }
} 